
package com.yimixian.app.mvp.presenter;

import com.ta.utdid2.android.utils.StringUtils;
import com.yimixian.app.EventBusDomain.OrderListPointTab;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.fragment.OrderMvpFragment;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.AppConfig;
import com.yimixian.app.model.Order;
import com.yimixian.app.mvp.basehttp.BaseHttpPresenter;
import com.yimixian.app.mvp.view.OrderListMvpView;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.rest.api.ClearRedPointAPI;
import com.yimixian.app.rest.api.OrdersListAPI;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.Strings;

import de.greenrobot.event.EventBus;

import org.json.JSONObject;

import android.net.Uri;
import android.text.TextUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

import java.util.ArrayList;
import java.util.List;

public class OrderListPresenter extends BaseHttpPresenter<OrderListMvpView> {

    private YmxDataService mYmxDataService;
    private DataManager mDataManager;
    // private ProgressDialogFragment mProgressDialog;
    private boolean isLoading = false;
    private OrdersListAPI mOrdersListAPI;
    private ClearRedPointAPI mClearRedPointAPI;
    private boolean showDialog = true;
    private boolean isClearRedPoint = true;
    private int LISTSTATUS = Constants.Action.PULLDOWAN;
    private ArrayList<Order> mOrders;

    public ArrayList<Order> getOrders() {
        return mOrders;
    }

    @Override
    public void attachView(OrderListMvpView mvpView) {
        super.attachView(mvpView);
    }

    @Override
    public void detachView() {
        super.detachView();
    }

    public void initData() {
        checkViewAttached();
        isClearRedPoint = true;
        mYmxDataService = YmxDataService.getInstance();
        mDataManager = DataManager.getInstance();
        if (mOrders == null)
            mOrders = new ArrayList<>();
        else
            mOrders.clear();
    }

    public void loadUrl() {
        if (DataManager.getInstance().get(CacheKeys.APP_CONFIG) != null) {
            String mUrl = ((AppConfig) DataManager.getInstance().get(CacheKeys.APP_CONFIG)).buyingGroupPlacesUrl;
            setAddressIdCookie(mUrl);
            mUrl = appendTokenIfNecessary(mUrl);
            getMvpView().loadURL(mUrl);
        }
    }

    public String appendTokenIfNecessary(String url) {
        String token = DataManager.getInstance().get(CacheKeys.TOKEN);
        Uri uri = Uri.parse(url);
        if (TextUtils.isEmpty(uri.getHost())) {
            return url;
        }
        if (Strings.isNullOrEmpty(token) || !uri.getHost().endsWith(".1mxian.com")) {
            return url;
        }
        return url + (url.contains("?") ? "&token=" : "?token=") + token;
    }

    public void loadData() {
        fetchData(true, mOrdersListAPI.ORDER_LIST);
    }

    public void onResumeLoadData() {
        showDialog = true;
        loadData();
    }

    @Override
    public void fetchDataFromNetwork(String key) {
        initRequestAPI(key);
        if (key != null && mOrdersListAPI != null && key.equals(OrdersListAPI.ORDER_LIST)) {
            mOrdersListAPI.getOrdersList();
        }
        if (key != null && mClearRedPointAPI != null && key.equals(ClearRedPointAPI.CLEARURL)) {
            mClearRedPointAPI.toClearRedPoint();
        }
    }

    @Override
    public void initRequestAPI(String requestKeys) {
        if (StringUtils.isEmpty(mDataManager
                .<String> get(CacheKeys.TOKEN)))
            return;

        // 清除小红点
        if (requestKeys != null && requestKeys.equals(ClearRedPointAPI.CLEARURL)) {
            if (isClearRedPoint) {
                mClearRedPointAPI = new ClearRedPointAPI(mDataManager
                        .<String> get(CacheKeys.TOKEN), Constants.RedPointType.ORDER, this);
            }
        } else {// 列表数据
            if (LISTSTATUS == Constants.Action.PULLDOWAN) {
                mOrdersListAPI = new OrdersListAPI(0, Constants.PAGE_SIZE, mDataManager
                        .<String> get(CacheKeys.TOKEN), this);
            } else {
                int last_id = 0;
                if (mOrders.size() > 0) {
                    last_id = mOrders.get(mOrders.size() - 1).id;
                }else {
//                    return;
                }
                mOrdersListAPI = new OrdersListAPI(last_id, Constants.PAGE_SIZE, mDataManager
                        .<String> get(CacheKeys.TOKEN), this);
            }
            if (isLoading) {
                return;
            }
            isLoading = true;
            if (showDialog) {
                getMvpView().showLoadingDataUI();
            }
        }
    }

    @Override
    public void onHttpSuccess(String url, JSONObject responseJson) {
        if (getMvpView() == null) {
            return;
        }
        getMvpView().hideLoadingDataUI();
        // 刷新出列表数据
        if (url.contains(OrdersListAPI.ORDER_LIST) && mOrdersListAPI != null) {

            // 清除订单红色按钮
            if (isClearRedPoint) {
                EventBus.getDefault().post(
                        new OrderListPointTab(0, Constants.RedPointType.ORDER, false));
                fetchData(true, mClearRedPointAPI.CLEARURL);
            }
            isClearRedPoint = false;
            List<Order> orders = mOrdersListAPI.parseJson(responseJson);
            // 下拉刷新
            if (mOrdersListAPI.back_last_id == 0) {
                getMvpView().onRefreshComplete();
                if (orders != null && orders.size() > 0) {
                    getMvpView().hideNoDataUI();

                } else {
                    getMvpView().showNoDataUI();
                }
                mOrders.clear();
                mOrders.addAll(orders);
            } else {
                mOrders.addAll(orders);
                getMvpView().onLoadMoreComplete();
                if (orders.size() < Constants.PAGE_SIZE) {
                    getMvpView().setListViewEnable(false);
                }
            }
            getMvpView().showHttpSucUI();
            isLoading = false;
            // UiUtils.dismiss(mProgressDialog);
            mDataManager.put(CacheKeys.ORDERS, mOrders);
        }
        // 清除小红点
        if (url.contains(ClearRedPointAPI.CLEARURL)) {
            isClearRedPoint = false;
        }
    }

    @Override
    public void OnHttpFailure(String url, String errorMessage, boolean errorFromUs) {
        if (getMvpView() == null) {
            return;
        }
        getMvpView().hideLoadingDataUI();
        getMvpView().showHttpFailUI(errorMessage);
        getMvpView().onLoadMoreComplete();
        getMvpView().onRefreshComplete();
    }

    public void onLoadMore() {
        LISTSTATUS = Constants.Action.PUSHUP;
        showDialog = false;
        if (checkNetWorkState())
            fetchData(true, mOrdersListAPI.ORDER_LIST);
        else {
            if (getMvpView() != null) {
                getMvpView().onLoadMoreComplete();
            }
        }
    }

    public void onPullDownToRefresh() {
        getMvpView().setListViewEnable(true);
        showDialog = false;
        LISTSTATUS = Constants.Action.PULLDOWAN;
        if (checkNetWorkState())
            fetchData(true, mOrdersListAPI.ORDER_LIST);
        else {
            if (getMvpView() != null) {
                getMvpView().onRefreshComplete();
            }
        }
    }

    public boolean onResumeCheck(boolean is_commit) {
        if (SharedPreferencesHelper.getBoolean(Constants.PAY_SUCCESS)) {
            SharedPreferencesHelper.commitBoolean(Constants.PAY_SUCCESS, false);
            onResumeLoadData();
        }
        if (is_commit) {
            onResumeLoadData();
            is_commit = false;
        }
        return is_commit;
    }

    private void setAddressIdCookie(String mUrl) {
        CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(SystemFramework
                .getInstance().getGlobalContext());
        cookieSyncManager.startSync();
        Address mAddress = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if (mAddress == null || mAddress.id == 0)
            return;
        AppConfig appConfig = mDataManager.get(CacheKeys.APP_CONFIG);
        if (appConfig == null) {
            return;
        }
        if (appConfig.cookieDomains == null) {
            return;
        }
        for (int i = 0; i < appConfig.cookieDomains.size(); i++) {
            String Domain = appConfig.cookieDomains.get(i);
            int addressId = mAddress.id;
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setCookie(mUrl, "address_id=" + addressId + ";Domain=" + Domain
                    + ";Path=/");
            CookieSyncManager.getInstance().sync();
        }

    }

}
